import React, { useState } from "react";
import { Card, Button, Progress, message } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import SparkMD5 from "spark-md5";
import { checkUploadFileApi } from "@/api/upload";
const createHash = (file: File): Promise<string> => {
  return new Promise((resolve) => {
    const blobSlice = File.prototype.slice,
      chunkSize = 2097152, // Read in chunks of 2MB
      chunks = Math.ceil(file.size / chunkSize),
      spark = new SparkMD5.ArrayBuffer(),
      fileReader = new FileReader();
    let currentChunk = 0;

    fileReader.onload = function (e) {
      spark.append(e.target!.result! as ArrayBuffer); // Append array buffer
      currentChunk++;

      if (currentChunk < chunks) {
        loadNext();
      } else {
        resolve(spark.end());
      }
    };

    fileReader.onerror = function () {
      console.warn("oops, something went wrong.");
    };

    function loadNext() {
      const start = currentChunk * chunkSize,
        end = start + chunkSize >= file.size ? file.size : start + chunkSize;

      fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
    }

    loadNext();
  });
};

const UploadPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [currentPercent, setCurrentPercent] = useState(0);

  const handleClick = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.click();

    input.addEventListener("change", async () => {
      if (input.files) {
        const file: File = input.files[0];
        if (file) {
          setLoading(true);
          const hash = await createHash(file);
          const checkFileResult = await checkUploadFileApi(hash);
          if (checkFileResult.code === 201) {
            message.success("文件已存在, 秒传成功");
            return;
          } else if (checkFileResult.code === 200) {
            handleUpload(hash, file, []);
          } else if (checkFileResult.code === 202) {
            handleUpload(hash, file, checkFileResult.data.existsChunks);
          }
        }
      }
    });
  };

  const handleUpload = async (hash: string, file: File, existsChunks: number[]) => {
    const chunkSize = 2 * 1024 * 1024;
    const chunksCount = Math.ceil(file.size / chunkSize);
    for (let i = 0; i < chunksCount; i++) {
      const start = i * chunkSize;
      const end = Math.min(file.size, start + chunkSize);
      const chunk = file.slice(start, end);
      
      const formData = new FormData();
      formData.append("chunk", chunk);
      formData.append("hash", hash);
      formData.append("index", i.toString());
    }
  }

  return (
    <Card title="文件上传">
      <Button
        onClick={() => handleClick()}
        icon={<UploadOutlined />}
        loading={loading}
        disabled={loading}
      >
        {loading ? "上传中..." : "上传文件"}
      </Button>
      {loading && (
        <Progress style={{ marginTop: 20 }} percent={currentPercent}></Progress>
      )}
    </Card>
  );
};

export default UploadPage;
